// package: learn-go
// filename: main
// author: Administrator@gmail.com
// time: 2023/8/9 16:58
package main

import (
	"bufio"
	"fmt"
	"io"
	"os/exec"
	"strings"
	"time"
)

func main() {
	// 创建一个用于记录输入的切片
	var inputs []string

	// 要执行的命令和参数
	command := "ls"
	params := []string{"-l"}

	// 执行cmd命令: ls -l
	inputs = append(inputs, fmt.Sprintf("%s %s", command, strings.Join(params, " ")))
	outputs := execCommandSin(command, params)

	// 打印输入记录
	fmt.Println("输入记录:")
	for _, input := range inputs {
		fmt.Println(input)
	}

	// 打印输出信息
	fmt.Println("输出信息:")
	for _, output := range outputs {
		fmt.Println(output)
	}
}

func execCommandSin(commandName string, params []string) []string {
	cmd := exec.Command(commandName, params...)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println(err)
		return nil
	}
	cmd.Start()

	reader := bufio.NewReader(stdout)
	var outputs []string

	// 实时循环读取输出流中的一行内容
	for {
		line, err := reader.ReadString('\n')
		if err != nil && err != io.EOF {
			fmt.Println(err)
			break
		}
		if line != "" {
			outputs = append(outputs, line)
			time.Sleep(1 * time.Second)
		}
		if err == io.EOF {
			break
		}
	}

	cmd.Wait()
	return outputs
}
